package com.example.quiz.service.impl;

import com.example.quiz.dao.UserMapper;
import com.example.quiz.model.User;
import com.example.quiz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public int register(User user) {
        // 检查用户名是否已存在
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            return 0;
        }

        // 设置默认角色
        user.setRole("USER");

        // 这里应该对密码进行加密，但为了简单起见，暂时不做加密
        return userMapper.insert(user);
    }

    @Override
    public User getByUsername(String username) {
        return null;
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    public int add(User entity) {
        return userMapper.insert(entity);
    }

    @Override
    public int deleteById(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public int update(User entity) {
        return userMapper.update(entity);
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> getAll() {
        return null;
    }

    @Override
    @Transactional
    public int changePassword(Long userId, String oldPassword, String newPassword) {
        return userMapper.updatePassword(userId, oldPassword, newPassword);
    }

    @Override
    public List<User> getPagedUsers(int page, int size) {
        int offset = (page - 1) * size;
        return userMapper.selectPagedUsers(offset, size);
    }

    @Override
    public int getTotalCount() {
        return userMapper.selectTotalCount();
    }

    @Override
    public int updateRole(Long id, String role) {
        if (!User.ROLE_ADMIN.equals(role) && !User.ROLE_USER.equals(role)) {
            return 0;
        }
        return userMapper.updateRole(id, role);
    }
}
